package util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import annotation.ActionAnnotation;
import annotation.ForwardAnnotation;
import bean.XmlBean;

public class AnnotationToBean {
	public static Map<String, XmlBean> xmlToBean(String tomcatPath,
			String packagePath) throws Exception {
		Map<String, XmlBean> pmap = new HashMap<String, XmlBean>();
		for (String actionpath : packagePath.split(",")) {
			for (String fileName : new File(tomcatPath + "WEB-INF\\classes\\"+ actionpath.replace('.', '\\')).list()) {
				String actionClass = actionpath + "." + fileName.split("\\.")[0];
				Class clazz = Class.forName(actionClass);
				if (clazz.isAnnotationPresent(ActionAnnotation.class)) {
					XmlBean xmlBean = new XmlBean();
					Map<String, String> forwardsMap = new HashMap<String, String>();
					ActionAnnotation actionAnnotation = (ActionAnnotation) clazz.getAnnotation(ActionAnnotation.class);
					String path = actionAnnotation.path();
					String formClass = actionAnnotation.formClass();
					xmlBean.setPath(path);
					xmlBean.setFormClass(formClass);
					xmlBean.setActionClass(actionClass);
					ForwardAnnotation[] forwardAnnotations = actionAnnotation.forward();
					for (ForwardAnnotation forward : forwardAnnotations) {
						forwardsMap.put(forward.name(), forward.url());
					}
					xmlBean.setActionForward(forwardsMap);
					pmap.put(path, xmlBean);
				}

			}
		}

		return pmap;
	}

}